<template>
  <div>
    <article class="main-breadcrumb">
      <el-breadcrumb separator="/" class="main-breadcrumb-wrap">
        <el-breadcrumb-item>
          <span class="main-breadcrumb-home">数据分析</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <span class="main-breadcrumb-home">装置数据分析</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item v-if="typeDialog">
          <span class="main-breadcrumb-sp">{{ crumbsStatus }}</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </article>
    <div class="nx-content" v-if="!typeDialog">
      <div class="flex-bet">
        <div class="left-title flex"></div>
        <el-form ref="searchForm" :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="">
            <el-cascader v-model="treeId" placeholder="请选择考场组织" :options="schoolArray" :props="{
                checkStrictly: true,
                value: 'id',
                label: 'name',
                children: 'nextDatas',
              }" @change="changeTreeItem" clearable></el-cascader>
          </el-form-item>
          <el-form-item label="">
            <el-select v-model="searchForm.deviceId" placeholder="请选择设备名称" @change="onSubmit" clearable>
              <el-option v-for="item in deviceArray" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="">
            <el-date-picker v-model="date" type="datetimerange" align="right" unlink-panels range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" :picker-options="pickerOptions" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" @change="handleDate" clearable>
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button v-allow="'140501'" type="primary" @click="onSubmit">查询</el-button>
            <el-button v-allow="'140501'" @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="info">
      <el-row class="content">
        <span class="title">装置使用时间</span>
      </el-row>
      <el-row class="content">
        <el-col :span="24">
          <div class="flexc">
            <div :id="'Bar1'" class="chart" ref="Bar1"></div>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="info">
      <el-row class="content">
        <span class="title">装置使用率</span>
      </el-row>
      <el-row class="content">
        <el-col :span="24">
          <div class="flexc">
            <div :id="'Bar2'" class="chart" ref="Bar2"></div>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="info">
      <el-row class="content">
        <span class="title">装置故障率</span>
      </el-row>
      <el-row class="content">
        <el-col :span="24">
          <div class="flexc">
            <div :id="'Bar3'" class="chart" ref="Bar3"></div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>
<script>
import * as echarts from 'echarts'
import { getDataAnalysisDeviceUseTimeChart, getDataAnalysisDeviceUseRateChart, getDataAnalysisDeviceFaultRateChart } from '@/api/analysis'
import { getSchoolInfos } from '@/api/school'
import { getDeviceInfos } from '@/api/device'

export default {
  components: {},
  // 表格数据
  data() {
    return {
      // 查询字段
      searchForm: {
        examinationRoomId: '',
        collegeId: '',
        facultyId: '',
        floorId: '',
        examinationRoomId: '',
        deviceId: '',
        startTime: '',
        endTime: ''
      },
      analysisData1: {}, // 设备使用时间
      analysisData2: {}, // 设备使用率
      analysisData3: {}, // 设备故障率
      crumbsStatus: '', // 三级面包屑名称
      typeDialog: false,
      addEditIsDialog: false, // 添加编辑页面状态
      addEditStatus: 'add',
      addEditId: '', // 添加编辑rowid
      treeId: [], // 考场组织id集合
      schoolArray: [], // 考场组织集合
      deviceArray: [], // 设备集合
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      date: [], // 日期范围
      userType: '', // 用户类型（0超级管理员，1考场管理员）
      examinationRoomId: '' // 考场id
    }
  },
  // 初始化加载
  mounted() {
    this.userType = Number(window.localStorage.getItem('userType'))
    this.examinationRoomId = Number(window.localStorage.getItem('examinationRoomId'))
    if (this.userType == 1) {
      this.searchForm.examinationRoomId = this.examinationRoomId
    }

    // 默认一月
    let end = new Date()
    let start = new Date()
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
    this.searchForm.startTime = this.$common.formatTime(start)
    this.searchForm.endTime = this.$common.formatTime(end)
    this.date = [this.searchForm.startTime, this.searchForm.endTime]

    // 查询
    this.onSubmit()

    // 获取考场组织
    this.getSchoolInfos()
  },
  // 自定义方法
  methods: {
    // 查询
    onSubmit() {
      if (!this.searchForm.startTime || this.searchForm.startTime == '') {
        this.$message({
          type: 'error',
          message: '请选择开始时间'
        })
        return
      }

      if (!this.searchForm.endTime || this.searchForm.endTime == '') {
        this.$message({
          type: 'error',
          message: '请选择结束时间'
        })
        return
      }

      // 获取装置使用时间
      getDataAnalysisDeviceUseTimeChart(this.searchForm).then((res) => {
        if (res.code == 200) {
          this.analysisData1 = res.data

          setTimeout(() => {
            if (this.analysisData1) {
              this.initBarData(this.analysisData1, '使用时间（小时）', 'Bar1')
            }
          }, 500)
        }
      })

      // 获取装置使用率
      getDataAnalysisDeviceUseRateChart(this.searchForm).then((res) => {
        if (res.code == 200) {
          this.analysisData2 = res.data

          setTimeout(() => {
            if (this.analysisData2) {
              this.initBarData(this.analysisData2, '使用率（%）', 'Bar2')
            }
          }, 500)
        }
      })

      // 获取装置故障率
      getDataAnalysisDeviceFaultRateChart(this.searchForm).then((res) => {
        if (res.code == 200) {
          this.analysisData3 = res.data

          setTimeout(() => {
            if (this.analysisData3) {
              this.initBarData(this.analysisData3, '故障率（%）', 'Bar3')
            }
          }, 500)
        }
      })
    },
    // 初始化图表数据
    initBarData(val, title, id) {
      let xDataList = []
      let yDataList = []
      let yTitleList = [title]

      // 遍历获取数据
      val.forEach((value) => {
        xDataList.push(value.deviceName)
        yDataList.push(value.deviceData)
      })

      const chartDom = document.getElementById(id)
      const myChart = echarts.init(chartDom)
      let option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: { show: true }
          }
        },
        legend: {
          data: yTitleList
        },
        xAxis: [
          {
            type: 'category',
            data: xDataList,
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: {},
        series: [
          {
            name: title,
            type: 'bar',
            data: yDataList
          }
        ]
      }

      option && myChart.setOption(option)
    },
    // 重置
    resetForm() {
      this.searchForm = {
        examinationRoomId: '',
        collegeId: '',
        facultyId: '',
        floorId: '',
        examinationRoomId: '',
        deviceId: '',
        startTime: '',
        endTime: ''
      }

      if (this.userType == 1) {
        this.searchForm.examinationRoomId = this.examinationRoomId
      }

      // 清空
      this.treeId = []
      this.deviceArray = []
      this.date = []

      this.onSubmit()
    },

    // 获取考场组织
    getSchoolInfos() {
      getSchoolInfos().then((res) => {
        if (res.code == 200) {
          this.schoolArray = res.data
        }
      })
    },
    // 考场组织下拉切换
    changeTreeItem(val) {
      this.searchForm.examinationRoomId = this.userType == 1 ? this.examinationRoomId : ''
      this.searchForm.collegeId = ''
      this.searchForm.facultyId = ''
      this.searchForm.floorId = ''
      this.searchForm.examinationRoomId = ''
      this.searchForm.deviceId = ''
      this.deviceArray = []

      if (val) {
        let len = val.length
        let id = val[len - 1]
        if (len == 1) {
          this.searchForm.examinationRoomId = id
        } else if (len == 2) {
          this.searchForm.collegeId = id
        } else if (len == 3) {
          this.searchForm.facultyId = id
        } else if (len == 4) {
          this.searchForm.floorId = id
        } else if (len == 5) {
          this.searchForm.examinationRoomId = id
          // 获取设备列表
          this.getDeviceInfoList()
        }
        this.searchForm.examinationRoomId = val[0]
      }

      // 查询
      this.onSubmit()
    },
    // 获取设备列表
    getDeviceInfoList() {
      if (!this.searchForm.examinationRoomId || this.searchForm.examinationRoomId == '') {
        return
      }

      getDeviceInfos({ id: this.searchForm.examinationRoomId }).then((res) => {
        if (res.code == 200) {
          this.deviceArray = res.data
        }
      })
    },
    // 日期切换
    handleDate() {
      if (this.date && this.date.length == 2) {
        this.searchForm.startTime = this.date[0]
        this.searchForm.endTime = this.date[1]
      } else {
        this.searchForm.startTime = ''
        this.searchForm.endTime = ''
      }

      this.onSubmit()
    }
  }
}
</script>
<style lang="less" scoped>
.main-breadcrumb {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 76px;
  border-bottom: solid 20px #f2f2f2;
  padding-left: 20px;
  .main-breadcrumb-wrap {
    font-size: 16px;
    line-height: 68px;
    .main-breadcrumb-home {
      cursor: pointer;
      color: #666666;
      font-weight: bold;
    }
    .main-breadcrumb-sp {
      color: #666666;
      font-weight: bold;
    }
  }
}

.info {
  border-top: solid 20px #f2f2f2;
  padding: 20px;
}

.title {
  font-size: 22px;
  font-weight: bold;
}

.content {
  margin-bottom: 20px;
}

.flexc {
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart {
  width: 95%;
  height: 400px;
}
</style>